package com.qm.controller;

import com.qm.service.SendSmsService;
import com.qm.vo.QmResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import redis.clients.jedis.JedisCluster;

import java.util.HashMap;
import java.util.UUID;

/**
 @author james
 @create 2021-04-27 23:20
 短信验证码API
 */
@RestController
@CrossOrigin    //跨域支持
public class SmsApiController {

    @Autowired
    private JedisCluster jedisCluster;

    @Autowired
    private SendSmsService sendSmsService;

    @GetMapping("/send/{phone}")
    public QmResult code(@PathVariable("phone") String phone) {
        String code = jedisCluster.get(phone);
        if (!StringUtils.isEmpty(code)) {
            System.out.println("验证码："+code);
            return new QmResult().success();
        }
//        code = UUID.randomUUID().toString().substring(0, 6);
        code = String.valueOf(getRandNum(1, 999999));
        HashMap<String, Object> param = new HashMap<>();
        param.put("code", code);

        boolean isSend = sendSmsService.send(phone, "SMS_215995835", param);
        if (isSend) {
            jedisCluster.setex(phone, 60*60, code);//一个小时
            System.out.println("验证码："+code);
            return QmResult.success();
        }
        return QmResult.fail();
    }

    //生成验证码函数
    public int getRandNum(int min, int max) {
        int randNum = min + (int)(Math.random() * ((max - min) + 1));
        return randNum;
    }
}
